package gr.atc.epart;


import gr.atc.epart.actions.Action.Type;
import gr.atc.epart.googlewrapper.GoogleServiceCallbackType;
import gr.atc.epart.googlewrapper.accounts.GoogleAccountManager;
import gr.atc.epart.googlewrapper.accounts.GoogleLoginDialog;
import gr.atc.epart.googlewrapper.moderator.GoogleModerator;
import gr.atc.epart.googlewrapper.moderator.ModeratorSeries;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class CreateActionActivity extends Activity {

	protected static final int DATE_DIALOG_ID_FROM = 0;

	protected static final int DATE_DIALOG_ID_TO = 1;

	int YearTo = 2010, monthTo = 0, dayTo = 1, YearFrom = 2010, monthFrom = 0,
			dayFrom = 1;

	EditText fromText = null;
	EditText toText = null;
	TextView fromLabel = null;
	TextView toLabel = null;
	Button fromButton;
	Button toButton;
	String typeString;
	Type type;
	String username;

	private GoogleModerator _moderator;
	private ProgressDialog _progressDialog;
	private GoogleAccountManager _accountManager;

	// when we create a deliberation, the parameters must be retained, so that both a 
	// google moderator and a backend entry is created.
	// lack of time....the simplest method....copy!
	Type _btype;
	String _bname;
	String _bdescription;
	String _busername;
	Date _bstartDate;
	Date _bendDate;
	String[] _btags;
	Boolean _bisLoginRequired;

	
	
	 private class OnGoogleLoginDialogHandler implements GoogleLoginDialog.OnCompleteListener
	 {

		@Override
		public void cancel()
		{
			// return to the previous activity.
			CreateActionActivity.this.finish();
		}

		@Override
		public void login(String username, String password)
		{
			 showProgressDialog();
			_moderator.authenticate(username,password);
		}
	 }

	 //
	 // used to receive callbacks related to moderator only  
	 //
	 private Handler _messageHandler = new Handler() 
	 {
		 public void handleMessage(Message msg) 
		 {  
			 switch(msg.what) 
			 {
				 case GoogleServiceCallbackType.UserAuthenticationRequired:
				 {
					 // display a dialog to receive the password....the username is known..!

					 dismissProgessDialog();

					 _accountManager = new GoogleAccountManager(CreateActionActivity.this);
					 String username = _accountManager.getAccountEmail();

					 GoogleLoginDialog logindialog = new GoogleLoginDialog(CreateActionActivity.this,"Please login into Google Moderator",username,new OnGoogleLoginDialogHandler());
					 logindialog.show();

					 //_moderator.authenticate("tsakonas.nick@gmail.com","m4l4k13$");
				 }
				 break;


				 case GoogleServiceCallbackType.ModeratorServiceIsReady:
					 //
					 // google moderator is ready...lets create the new series.
					 // NOTE: at the moment, no video submission is allowed..at a later point maybe
					 _moderator.addSeries(_bname,_bdescription, false);
					 break;

				 case GoogleServiceCallbackType.ModeratorNewSeriesAdded:
					 //
					 // series added to google moderator...add an entry to the backend
					 //
	        		  ArrayList<ModeratorSeries> newSeriesList = (ArrayList<ModeratorSeries>) msg.getData().getSerializable("SERIES");
	        		  
	        		  // NOTE: the list is used for future use...in order to retrieve more than 
	        		  // one series at a time at the moment only one series is contained
	        		  int seriesId = newSeriesList.get(0).getSeriesId();	
					  createAction(_btype,_bname,_bdescription,_busername,_bstartDate,_bendDate,_btags,_bisLoginRequired,seriesId);
					  
					 break;

				 case GoogleServiceCallbackType.OperationError:
		        	  	{
		        	  		if (msg.getData()!=null)
		        	  		{
			        	  		String error = msg.getData().getString("DESCRIPTION");
			        	  		showErrorAlert("Google moderator error:"+error);
			        	  		
		        	  		}
		        	  		dismissProgessDialog();
		        	  	}
					 break;

			 }
		 }
	 };

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		username = AccountUtil.getAccountName(this.getBaseContext());
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		Calendar current = Calendar.getInstance();
		dayFrom = current.get(Calendar.DAY_OF_MONTH);
		dayTo = current.get(Calendar.DAY_OF_MONTH);

		monthFrom = current.get(Calendar.MONTH);
		monthTo = current.get(Calendar.MONTH);

		YearFrom = current.get(Calendar.YEAR);
		YearTo = current.get(Calendar.YEAR);

		setContentView(R.layout.createactionview);

		Button createButton = (Button) findViewById(R.id.createbutton);
		createButton.setOnClickListener(buttonListener);

		EditText nameEdit = (EditText) findViewById(R.id.newactionname);

		nameEdit.clearFocus();

		fromText = (EditText) findViewById(R.id.newactionfromtxt);
		toText = (EditText) findViewById(R.id.newactiontotxt);

		fromLabel = (TextView) findViewById(R.id.newactionfromlbl);
		toLabel = (TextView) findViewById(R.id.newactiontolbl);

		fromButton = (Button) findViewById(R.id.newactionfrombtn);
		fromButton.setOnClickListener(buttonListener);

		toButton = (Button) findViewById(R.id.newactiontobtn);
		toButton.setOnClickListener(buttonListener);
		
	
		Spinner typeSpinner = (Spinner) findViewById(R.id.actiontypespinner);

		ArrayAdapter<String> typeAttributes = new ArrayAdapter<String>(this,
				R.layout.sortbyspinnerview, getResources().getStringArray(
						R.array.typeinput));

		typeSpinner.setAdapter(typeAttributes);

		typeSpinner.setSelection(0);
		
		toLabel.setVisibility(View.VISIBLE);
		toText.setVisibility(View.VISIBLE);
		toButton.setVisibility(View.VISIBLE);

		fromLabel.setVisibility(View.VISIBLE);
		fromText.setVisibility(View.VISIBLE);
		fromButton.setVisibility(View.VISIBLE);


		typeSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						typeString = item.toString();
						type = Type.valueOf(typeString);

						if (type == Type.Deliberation) {

							toLabel.setVisibility(View.INVISIBLE);
							toText.setVisibility(View.INVISIBLE);
							toButton.setVisibility(View.INVISIBLE);
						
							fromLabel.setVisibility(View.INVISIBLE);
							fromText.setVisibility(View.INVISIBLE);
							fromButton.setVisibility(View.INVISIBLE);


						} else if (type == Type.ePetition) {

							toLabel.setVisibility(View.VISIBLE);
							toText.setVisibility(View.VISIBLE);
							toButton.setVisibility(View.VISIBLE);
							
							fromLabel.setVisibility(View.VISIBLE);
							fromText.setVisibility(View.VISIBLE);
							fromButton.setVisibility(View.VISIBLE);


						} else if (type == Type.Survey) {

							toLabel.setVisibility(View.VISIBLE);
							toText.setVisibility(View.VISIBLE);
							toButton.setVisibility(View.VISIBLE);

							fromLabel.setVisibility(View.VISIBLE);
							fromText.setVisibility(View.VISIBLE);
							fromButton.setVisibility(View.VISIBLE);


						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

	}

	private OnClickListener buttonListener = new OnClickListener() {
		public void onClick(View v) {

			if (v == findViewById(R.id.newactionfrombtn)) {
				showDialog(DATE_DIALOG_ID_FROM);
			} else if (v == findViewById(R.id.newactiontobtn)) {
				showDialog(DATE_DIALOG_ID_TO);
			} else if (v == findViewById(R.id.createbutton)) {

				
				EditText tagsEdit = (EditText) findViewById(R.id.newactiontags);

				String tagsString = tagsEdit.getText().toString();

				String[] tags = tagsString.split(" ");

				EditText nameEdit = (EditText) findViewById(R.id.newactionname);
				String name = nameEdit.getText().toString();
				EditText descriptionEdit = (EditText) findViewById(R.id.newactiondescription);
				String description = descriptionEdit.getText().toString();
				CheckBox loginRequiredCheckBox = (CheckBox) findViewById(R.id.newactioncheckbox);
				Boolean isLoginRequired = loginRequiredCheckBox.isChecked();

				String fromString = fromText.getText().toString();
				String toString = toText.getText().toString();

				SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
				Date startDate = null;
				Date endDate = null;
								

				try {
					if (fromString != null) {
						startDate = formatter.parse(fromString);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}

				try {
					if (toString != null && !toString.equals("")) {
						endDate = formatter.parse(toString);
					}

				} catch (ParseException e) {
					e.printStackTrace();
				}

				boolean valid = true;

				if (name.equals("")) {

					valid = false;
					createAlert("name cannot be empty");

				} else if (tagsString.equals("")) {

					valid = false;
					createAlert("tags cannot be empty");

				} else if (description.equals("")) {

					valid = false;
					createAlert("description cannot be empty");

				} else if (type == Type.ePetition || type == Type.Survey) {
					
					Calendar now = Calendar.getInstance();
					
//					now.set(now.get(Calendar.YEAR),
//							now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));

					Date currentDate = new Date();
					
					try {
						currentDate = formatter.parse(now.get(Calendar.DATE) + "-" + now.get(Calendar.MONTH) + "-" + now.get(Calendar.YEAR));
					} catch (ParseException e) {
						e.printStackTrace();
					}
								
					if (startDate == null) {
					
						valid = false;
						createAlert("startDate cannot be empty");
						
					} else if (endDate == null) {
						
						valid = false;
						createAlert("endDate cannot be empty");
						
					} else if  (endDate.before(startDate) || endDate.equals(startDate)){
						
						valid = false;						
						createAlert("Start Date must be earlier than End Date");
						
						
					} else if (startDate.before(currentDate)) {
						
						valid = false;
						createAlert("Start Date cannot be earlier than Current Date");
						
					} else if (endDate.before(currentDate)) {
						
						valid = false;
						createAlert("End Date cannot be earlier than Current Date");
						
					}
				}
				else if (type == Type.Deliberation)
				{
					// no extra actions required
				}

				if (valid) 
				{
					if (type == Type.Deliberation || type == Type.Survey)
					{
						// when a deliberation or survey is created, an equivalent entry must be created into Google Moderator
						// after the entry has been created, the series id returned by google moderator must be saved 
						// to the backend

						createModeratorEntry(type, name,description, username, startDate, endDate, tags,isLoginRequired);
					}
					else
					{
						createAction(type, name,description, username, startDate, endDate, tags,isLoginRequired);
					}
				}
			}
		}
	};
	
	private void createAction(Type actionType, String name, String description, String creator,Date startDate, Date stopDate, String[] tags,boolean isLoginRequired)
	{
		createAction(actionType, name, description, creator,startDate, stopDate, tags,isLoginRequired,0);
	}

	private void createAction(Type actionType, String name, String description, String creator,Date startDate, Date stopDate, String[] tags,boolean isLoginRequired,int seriesId)
	{

		EPartClient client = new EPartClient();

		if (client.createAction(type, name,description, username, startDate, stopDate, tags,isLoginRequired,seriesId)) 
		{
			createSuccessAlert(typeString + " successfully created");
		} else 
		{
			createAlert("cannot create " + typeString + ": unkonwn error occurred");
			dismissProgessDialog();
		}
		
	}
	
	protected void createModeratorEntry(Type type, String name,String description, String username, Date startDate, Date endDate,
			String[] tags, Boolean isLoginRequired)
	{
		// this method will first create a google moderator entry and then, it will add to the backend the deliberation
		// with the google moderator series id.
		
		// all the original data must be retained...
		_btype = type;
		_bname = name;
		_bdescription = description;
		_busername = username;
		_bstartDate =startDate;
		_bendDate = endDate;
		_btags = tags;
		_bisLoginRequired = isLoginRequired;

		showProgressDialog();
		_moderator = new GoogleModerator(_messageHandler);
		_moderator.authenticate();
		// when the service is ready (into the message handler) the creation is performed
		
	}

	

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			YearTo = year;
			monthTo = monthOfYear;
			dayTo = dayOfMonth;

			toText.setText(dayTo + "-" + (monthTo + 1) + "-" + YearTo);
			/*
			Toast.makeText(
					getBaseContext(),
					"You have selected : " + dayTo + "-" + (monthTo + 1) + "-"
							+ YearTo, Toast.LENGTH_SHORT).show();
			*/				
		}

	};

	private DatePickerDialog.OnDateSetListener mDateSetListenerFrom = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			YearFrom = year;
			monthFrom = monthOfYear;
			dayFrom = dayOfMonth;

			fromText.setText(dayFrom + "-" + (monthFrom + 1) + "-" + YearFrom);
			/*
			Toast.makeText(
					getBaseContext(),
					"You have selected : " + dayFrom + "-" + (monthFrom + 1)
							+ "-" + YearFrom, Toast.LENGTH_SHORT).show();
			 */
		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID_TO:
			return new DatePickerDialog(this, mDateSetListener, YearTo,
					monthTo, dayTo);
		case DATE_DIALOG_ID_FROM:
			return new DatePickerDialog(this, mDateSetListenerFrom, YearFrom,
					monthFrom, dayFrom);
		}
		return null;
	}

	public void createAlert(String message) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(message);
		dlgAlert.setTitle("EParticipation!");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

	public void createSuccessAlert(String message) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(message);
		dlgAlert.setTitle("EParticipation!");
		dlgAlert.setPositiveButton("OK", okButtonListener);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

	private DialogInterface.OnClickListener okButtonListener = new DialogInterface.OnClickListener() {

		public void onClick(DialogInterface dialog, int which) {

			dialog.dismiss();
			setResult(200);
			finish();
		}

	};

	private void showProgressDialog() {
		
		_progressDialog = new ProgressDialog(this);
		_progressDialog.setMessage("Please wait...");
		_progressDialog.setIndeterminate(true);
		_progressDialog.setCancelable(false);
		_progressDialog.show();
	}

	private void dismissProgessDialog()
	{
		
		_progressDialogHandler.sendEmptyMessage(0);
	}

	   // Define the Handler that receives messages from the thread and update the progress
	final Handler _progressDialogHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			if (_progressDialog!=null)
				_progressDialog.dismiss();

		}
	};

	public void showErrorAlert(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Error");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

}
